<template>
	<view class="content">
		<view class="form">
			<u--form ref="uForm" errorType="none" :rules="rules" :model="form" labelPosition="top" labelWidth="80" :labelStyle="{color: '#ffffff', fontSize: '25rpx', paddingBottom: '10rpx'}">
				<u-form-item label="安全密码" prop="password">
					<u--input class="input" v-model="form.password" color="#ffffff" maxlength="6"></u--input>
				</u-form-item>
				<u-form-item label="验证码" prop="code">
					<u-input v-model="form.code" class="input" color="#ffffff" maxlength="6">
						<template slot="suffix">
							<u-code
								ref="uCode"
								@change="codeChange"
								seconds="120"
								changeText="X秒重新获"
							></u-code>
							<u-button
								@tap="getCode"
								:text="tips"
								type="success"
								size="mini"
								class="light-btn"
							></u-button>
						</template>
					</u-input>
				</u-form-item>
				<u-form-item>
					<button class="light-btn btn" @click="onUpdate">立即修改</button>
				</u-form-item>
			</u--form>
		</view>
	</view>
</template>

<script>
	import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
	export default {
		components: {
		},
		data() {
			return {
				tips: '',
				form: {
					password: null,
					code: null,
					authCode: ''
				},
				smsToken: '',
				smsForm: {
					type: 'common',
					number: ''
				},
				user: {},
				rules: {
					'password': {
						type: 'string',
						required: true,
						message: '请输入密码',
						trigger: ['blur']
					},
					code: [
						{
							type: 'string',
							required: true,
							message: '请输入验证码',
							trigger: ['blur']
						},
					]
				}
			}
		},
		onShow() {
			this.getUserInfo().then(res => {
				this.user = res.data
			})
		},
		methods: {
			...mapActions('user', ['updateUserSafePwd', 'getUserInfo']),
			...mapActions('common', ['sendSms']),
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				let _this = this
				if (this.$refs.uCode.canGetCode) {
				  this.smsForm.number = this.user.mobile;
				  this.sendSms(this.smsForm).then(res => {
					  // 这里此提示会被this.start()方法中的提示覆盖
					  // uni.$u.toast('验证码已发送');
					  // 通知验证码组件内部开始倒计时
					  _this.smsToken = res.data
					  _this.$refs.uCode.start();
				  })
				} else {
				}
			},
			onUpdate(){
				this.$refs.uForm.validate().then(res => {
					this.form.authCode = this.smsToken + ':' + this.form.code
					this.updateUserSafePwd(this.form).then(r => {
						uni.$u.toast('修改成功')
					})
				}).catch(errors => {
					uni.$u.toast(errors[0].message)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content{
		.form{
			padding: 20rpx 20rpx;
			.input{
				background-color: #232639 !important;
				border: 1rpx solid #666666 !important;
				color: #ffffff;
			}
		}
		.btn{
			margin-top: 20rpx;
			width: 50%;
		}
	}
</style>
